const db = require('../../MySql')

class sys_depart{
    constructor(id,dept_type,parent_id,dept_name,dept_code,sort){
        this.id = id
        this.dept_type = dept_type
        this.parent_id = parent_id
        this.dept_name = dept_name
        this.dept_code = dept_code
        this.sort = sort
    }

    //查询所有
    static async findAll(){
        const sql = 'SELECT * FROM sys_depart'
        const [rows] = await db.query(sql)
        return rows
    }

    //分页查询
    static async findDepartsByPage(current,size){
        const offset = (current - 1) * size
        const sql = 'SELECT * FROM sys_depart LIMIT ? OFFSET ?'
        const [rows] = await db.query(sql,[size,offset])
        return rows
    }

    //根据id查询部门
    static async findById(id){
        const sql = 'SELECT * FROM sys_depart WHERE id = ?'
        const [rows] = await db.query(sql,[id])
        return rows
    }

    //根据parent_id查询子部门
    static async findByParentId(parent_id){
        const sql = 'SELECT * FROM sys_depart WHERE parent_id = ?'
        const [rows] = await db.query(sql,[parent_id])
        return rows
    }

    //根据部门名称模糊查询
    static async findByDeptName(dept_name){
        const sql = 'SELECT * FROM sys_depart WHERE dept_name LIKE ?'
        const [rows] = await db.query(sql,['%' + dept_name + '%'])
        return rows
    }

    //根据id更新部门名称
    static async updateName(id,dept_name){
        const sql = 'UPDATE sys_depart SET dept_name = ? WHERE id = ?'
        const [result] = await db.query(sql,[dept_name,id])
        return result
    }

    //根据id更新父级id
    static async updateParentId(id,parent_id){
        const sql = 'UPDATE sys_depart SET parent_id = ? WHERE id = ?'
        const [result] = await db.query(sql,[parent_id,id])
        return result
    }

    //根据id更新部门代码
    static async updateDeptCode(id,dept_code){
        const sql = 'UPDATE sys_depart SET dept_code = ? WHERE id = ?'
        const [result] = await db.query(sql,[dept_code,id])
        return result
    }

    ///根据id更新排序
    static async updateSort(id,sort){
        const sql = 'UPDATE sys_depart SET sort = ? WHERE id = ?'
        const [result] = await db.query(sql,[sort,id])
        return result
    }

    //新增记录
    static async add(depart){
        const sql = 'INSERT INTO sys_depart SET ?'
        const [result] = await db.query(sql,depart)
        return result
    }

    //根据id删除记录
    static async deleteById(id){
        const sql = 'DELETE FROM sys_depart WHERE id = ?'
        const [result] = await db.query(sql,[id])
        return result
    }
}

module.exports = sys_depart
